package xyz.flowlight.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.flowlight.domain.entity.LikeRecord;
import xyz.flowlight.domain.response.ResponseResult;
import xyz.flowlight.mapper.LikeMapper;
import xyz.flowlight.service.LikeService;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service("likeService")
public class LikeServiceImpl extends ServiceImpl<LikeMapper, LikeRecord> implements LikeService {
    @Autowired
    LikeMapper likeMapper;

    @Override
    public ResponseResult<Boolean> toggleLike(Integer userId, Integer productId) {
        // 查询是否已存在点赞记录
        LikeRecord likeRecord = likeMapper.selectOne(new LambdaQueryWrapper<LikeRecord>()
                .eq(LikeRecord::getUserId, userId)
                .eq(LikeRecord::getProductId, productId));

        if (likeRecord != null) {
            // 如果存在则删除
            likeMapper.delete(new LambdaQueryWrapper<LikeRecord>()
                    .eq(LikeRecord::getLikeId,likeRecord.getLikeId()));
            return ResponseResult.success();
        } else {
            // 如果不存在则新增
            LikeRecord newRecord = new LikeRecord();
            newRecord.setUserId(userId);
            newRecord.setProductId(productId);
            likeMapper.insert(newRecord);
            return ResponseResult.success(true);
        }
    }

    @Override
    public ResponseResult<Boolean> isLiked(Integer userId, Integer productId) {
        // 查询是否存在点赞记录
        LikeRecord likeRecord = likeMapper.selectOne(new LambdaQueryWrapper<LikeRecord>()
                .eq(LikeRecord::getUserId, userId)
                .eq(LikeRecord::getProductId, productId));
        return ResponseResult.success(likeRecord != null);
    }
}
